<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_poster/model')->方法名();
*/
namespace jy_poster;
defined('BY_JYA') or exit('error');
class model extends \plugin{
	public function createImage($imgurl) //从字符串中的图像流新建一图像
	{		
		$localpath=SITEROOT.RESOURCE;
		if(strpos($imgurl,$localpath)!== false){
			$imgurl=str_replace($localpath,ROOT_AT,$imgurl);
			return @imagecreatefromstring(file_get_contents($imgurl));
		}else{
			$resp = cfc('http')->ihttp_request($imgurl,'','',6);
			if (($resp['code'] == 200) && !(empty($resp['content']))){
				return @imagecreatefromstring($resp['content']);
			}
		}
		return '';
	}
	public function yuanimg($sourceImage, $width, $height){
		// 计算最短边作为直径
		$diameter = min($width, $height);
		// 创建正方形画布
		$squareImage = imagecreatetruecolor($diameter, $diameter);
		imagealphablending($squareImage, false);
		imagesavealpha($squareImage, true);
		// 设置透明背景
		$transparent = imagecolorallocatealpha($squareImage, 0, 0, 0, 127);
		imagefill($squareImage, 0, 0, $transparent);
	 
		// 将原图绘制到画布中心
		$x = ($diameter - $width) / 2;
		$y = ($diameter - $height) / 2;
		imagecopy($squareImage, $sourceImage, $x, $y, 0, 0, $width, $height);
	 
		// 创建圆形画布
		$circleImage = imagecreatetruecolor($diameter, $diameter);
		imagealphablending($circleImage, false);
		imagesavealpha($circleImage, true);
		$transparent = imagecolorallocatealpha($circleImage, 0, 0, 0, 127);
		imagefill($circleImage, 0, 0, $transparent);
	 
		// 创建圆形蒙版
		for ($x = 0; $x < $diameter; $x++) {
			for ($y = 0; $y < $diameter; $y++) {
				$alpha = (int)(abs(sqrt(pow($x - $diameter / 2, 2) + pow($y - $diameter / 2, 2)) / ($diameter / 2)) * 127);
				if ($alpha > 127) {
					$alpha = 127;
				}
				$color = imagecolorallocatealpha($circleImage, 0, 0, 0, $alpha);
				imagesetpixel($circleImage, $x, $y, $color);
			}
		}
		imagecopy($circleImage, $squareImage, 0, 0, 0, 0, $diameter, $diameter);
		return $circleImage;
	}
	public function mergeImage($target, $data, $imgurl){
		$img = $this->createImage($imgurl);
		if(!$img){
			return $target;	
		}
		$w = imagesx($img);
		$h = imagesy($img);
		if($data['isyuan']){
			$img=$this->yuanimg($img,$w,$h);
		}
		imagecopyresized($target, $img, $data['left'], $data['top'], 0, 0, $data['width'], $data['height'], $w, $h);
		imagedestroy($img);
		return $target;
	}
	public function mergeText($target, $pos, $text,$addtext='') 
	{
		$font_file = ROOT_D . '/addons/jy_poster/resource/msyh.ttf';
		$colors = $this->hex2rgb($pos['color']);
		$color = imagecolorallocate($target, $colors['red'], $colors['green'], $colors['blue']);
		if(!$pos['size']){
			$pos['size']='13px';
		}
		$pos['width']=$pos['width']?:280;
		$string=$text;
		$_string='';
		$__string='';
		for($i=0;$i<mb_strlen($string);$i++){
			$box=imagettfbbox($pos['size'],0,$font_file,$_string);
			$_string_length=$box[2]-$box[0];
			$box=imagettfbbox($pos['size'],0,$font_file,mb_substr($string,$i,1));
			if( $_string_length+$box[2]-$box[0]<$pos['width']){
				$_string.=mb_substr($string,$i,1);
			}else{
				$__string.=$_string."\n";
				$_string=mb_substr($string,$i,1);
			}
		}
		$__string.=$_string;
		$box=imagettfbbox($pos['size'],0,$font_file,mb_substr($__string,0,1));
		if($addtext){
			imagettftext($target, 20, 0, $pos['left'], $pos['top']+($box[3]-$box[7]), $color, $font_file, $addtext);
			$pos['left'] +=28;
		}
		imagettftext($target, $pos['size'], 0, $pos['left'], $pos['top']+($box[3]-$box[7]), $color, $font_file, $__string);
		//加粗
		if($pos['bold']==1){
			$pos['left'] +=1;
			imagettftext($target, $pos['size'], 0, $pos['left'], $pos['top']+($box[3]-$box[7]), $color, $font_file, $__string);
		}
		return $target;
	}
	public function hex2rgb($colour) 
	{
		if ($colour[0] == '#') 
		{
			$colour = substr($colour, 1);
		}
		if (strlen($colour) == 6) 
		{
			list($r, $g, $b) = array($colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5]);
		}
		else if (strlen($colour) == 3) 
		{
			list($r, $g, $b) = array($colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2]);
		}
		else 
		{
			return false;
		}
		$r = hexdec($r);
		$g = hexdec($g);
		$b = hexdec($b);
		return array('red' => $r, 'green' => $g, 'blue' => $b);
	}
	public function resizejpg($imgsrc,$path,$file2,$imgWidth,$imgHeight,$posterid,$plugin=''){
		global $_AR;
		$file=cfc('files')->local($imgsrc);
		$arr = getimagesize($file); //获取图片信息宽、高 
		$imgsrc = tomedia($imgsrc);
		$imgsrc=$this->createImage($imgsrc);//转为图片流
		//$imgsrc = imagecreatefromstring($imgsrc);
		$image = imagecreatetruecolor($imgWidth, $imgHeight);  //创建一个彩色的底图
		imagecopyresampled($image, $imgsrc, 0, 0, 0, 0,$imgWidth,$imgHeight,$arr[0], $arr[1]);
		imagepng($image, $path.$file2);
		imagedestroy($image);
		//要是网址形式
		if(($_SESSION['fromh5wxapp'] || $_SESSION['container']=='wxapp') && $_SESSION['wxapp_id']){
			$img = SITEROOT.RESOURCE . '/oss/'.$_SESSION['uniacid'].'/images/jy_poster/wxapp' .$posterid.'/'.$plugin.'/'.$file2;
		}else{
			$img = SITEROOT.RESOURCE . '/oss/'.$_SESSION['uniacid'].'/images/jy_poster/' .$posterid.'/'.$plugin.'/'.$file2;
		}
		cfc('files')->source_del($file);
		return $img;
	}
	public function createPoster($poster, $qr, $updata,$goodsid=0,$plugin='jy_weishop',$isup=false)
	{
		global $_AR;
		$poster['id']=$poster['id']?:'other';
		if(($_SESSION['fromh5wxapp'] || $_SESSION['container']=='wxapp') && $_SESSION['wxapp_id']){
			$path = ROOT_AT .'oss/'.$_SESSION['uniacid'].'/images/jy_poster/wxapp'.$poster['id'].'/';
			$path2='oss/'.$_SESSION['uniacid'].'/images/jy_poster/wxapp'.$poster['id'].'/';
		}else{
			$path = ROOT_AT .'oss/'.$_SESSION['uniacid'].'/images/jy_poster/'.$poster['id'].'/';
			$path2='oss/'.$_SESSION['uniacid'].'/images/jy_poster/'.$poster['id'].'/';
		}
		if($plugin){
			$path .=$plugin.'/';
			$path2 .=$plugin.'/';
		}
		$copypath = $path;
		$data=$poster['data'];
		$mid=$updata['mid']?:$_SESSION['uid'];
		$md5 = 'poster'.$mid.'id'.$poster['id'].'goodsid'.$goodsid.'/';
		if (!(is_dir($path.$md5))){
			cfc('files')->mkdirs($path.$md5);
		}
		$file = $md5 . '1.png';
		$file2 = $md5 . 'bg.png';
		$isadd=cfc('files')->source_check($path2.$file);
		if($isadd && !$isup){
			$img = $path2.$file;
			return $img;	
		}
		if($isup){
			$nonce = random(4,true);
			$file = $md5 . '/'.$nonce.'.png';
			$handle = scandir($copypath.$md5);
			foreach($handle as $val){
				if($val !="." && $val !=".."){
					unlink($copypath.$md5.$val);
				}
		   }
		}
		if(!$isadd){
			$height=$poster['height']?:1008;
			$width=$poster['width']?:640;
			$rate=$poster['diywidth']?$poster['width']/$poster['diywidth']:2;
			set_time_limit(0);
			@ini_set('memory_limit', '256M');
			$target = imagecreatetruecolor($width, $height);//创建画布
			if($poster['bg']){
				$bgimg=$this->resizejpg($poster['bg'],$path,$file2,$width,$height,$poster['id'],$plugin);//生成背景图
				$bg = $this->createImage($bgimg);
				imagecopy($target, $bg, 0, 0, 0, 0, $width, $height);//将图片绘制在画布上
				imagedestroy($bg);//销毁背景图
			}else{
				$color = imagecolorallocate($target,255,255,255);//先分配一个白底
				imagefill($target,0,0,$color);//使用白色填充
			}
			foreach ($data as $d){
				$d = $this->getRealData($d,$rate);
				if ($d['type'] == 'head') {	
					$avatar =tomedia($updata['avatar']);
					$target = $this->mergeImage($target, $d, $avatar);
				}else if ($d['type'] == 'img') {
					$d['src']=tomedia($d['src']);
					$target = $this->mergeImage($target, $d, $d['src']);
				}else if ($d['type'] == 'qr') {	
					$target = $this->mergeImage($target, $d, tomedia($qr));
				}else if ($d['type'] == 'nickname'){
					$target = $this->mergeText($target, $d, $updata['nickname']);
				}else if ($d['type'] == 'text') {
					$target = $this->mergeText($target, $d,$d['value']);
				}else if ($plugin =='jy_weishop' || $poster['id']=='goods'){
					$goods=pdo_get('jy_weishop_goods',array('id'=>$goodsid,'uniacid'=>$_SESSION['uniacid']));
					if ($d['type'] == 'title') {
						$target = $this->mergeText($target, $d, $goods['title']);
					}else if ($d['type'] == 'thumb'){
						$thumb = $goods['commission_thumb']? tomedia($goods['commission_thumb']) : tomedia($goods['image']);
						$target = $this->mergeImage($target, $d, $thumb);
						if(!$target){
							//return '';
						}
					}else if ($d['type'] == 'marketprice'){//现价
						$target = $this->mergeText($target, $d, $goods['price'],'￥');
					}else if ($d['type'] == 'productprice') {//原价
						$target = $this->mergeText($target, $d, '原价：￥'.$goods['originalprice']);
					}
				}else if ($plugin =='jy_vote'){
					if ($d['type'] == 'fee') 
					{
						$target = $this->mergeText($target, $d, $updata['fee']);
					}else if ($d['type'] == 'nums') 
					{
						$target = $this->mergeText($target, $d, $updata['nums']);
					}
				}
			}
			imagepng($target, $copypath . $file);
			imagedestroy($target);
		}
		$img =  $copypath . $file;
		$filename=$path2.$file;
		//$title='海报'.$_SESSION['uniacid'].'_'.$poster['id'];
		if(ATTACHMENT_TYPE){
			cfc('files')->source_save($img,'nochoose','png','',$filename);
			unlink($img);
		}
		unlink($path . $file2);
		return $filename;
	}
	public function getRealData($data,$rate=2) 
	{
		$data['left'] = intval(str_replace('px', '', $data['left'])) * $rate;
		$data['top'] = intval(str_replace('px', '', $data['top'])) * $rate;
		$data['width'] = intval(str_replace('px', '', $data['width'])) * $rate;
		$data['height'] = intval(str_replace('px', '', $data['height'])) * $rate;
		$data['size'] = intval(str_replace('px', '', $data['size'])) * $rate;
		$data['src'] = tomedia($data['src']);
		return $data;
	}
	public function getitemData($data) 
	{
		$data['left'] = intval(str_replace('px', '', $data['left']));
		$data['top'] = intval(str_replace('px', '', $data['top']));
		$data['width'] = intval(str_replace('px', '', $data['width']));
		$data['height'] = intval(str_replace('px', '', $data['height']));
		$data['size'] = intval(str_replace('px', '', $data['size']));
		$data['src'] = tomedia($data['src']);
		return $data;
	}
	public function get_subscribeqr($item) 
	{
		$data=array(
			'title'=>trim($item['title']),
			'linkurl'=>'',
			'qrtype'=>0,
			'type'=>2,
			'eventtype'=>1,
			'plugin'=>'jy_poster',
			'backid'=>'',
		);
		//微信二维码
		$getqrdata=array(
			'scantype'=>'follow',
			'id'=>$item['id'],
			'fromuser'=>$_SESSION['uid'],
		);
		$getqrdata = ijson_encode($getqrdata);
		$keyid='follow'.$item['id'].'mid'.$_SESSION['uid'];
		$res=model('core/account')->get_qr($data['type'],$data['plugin'],$getqrdata,$data['title'],'',$keyid);
		if(!$res['id']){
				exi('创建微信二维码失败！请检测微信公众号参数','error');
		}else{
				$update=array(
					'qrtype'=>$data['qrtype'],
					'eventtype'=>$data['eventtype'],
					'backid'=>'',
				);
				pdo_update('core_qr',$update,array('id'=>$res['id']));
		}
		return $res['file'];
	}
	public function get_fee($id,$fromuser=0) 
	{
		$poster=pdo_get('jy_poster_poster',array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
		if($poster['reccredit'] && $fromuser){
			$tag='reccredit'.$id.'_'.$_SESSION['uid'];
			$isreccredit=pdo_getcolumn('core_credit_log',array('mid'=>$fromuser,'tag'=>$tag,'plugin'=>'jy_poster','uniacid'=>$_SESSION['uniacid']),'id');
			if(!$isreccredit){
				model('core/member')->member_credit($fromuser,'credit1',$poster['reccredit'],true,'jy_poster','推荐人海报扫码',$tag);
			}
		}
		if($poster['recmoney'] && $fromuser){
			$tag='recmoney'.$id.'_'.$_SESSION['uid'];
			$recmoney=pdo_getcolumn('core_credit_log',array('mid'=>$fromuser,'tag'=>$tag,'plugin'=>'jy_poster','uniacid'=>$_SESSION['uniacid']),'id');
			if(!$recmoney){
				model('core/member')->member_credit($fromuser,'credit2',$poster['recmoney'],true,'jy_poster','推荐人海报扫码',$tag);
			}
		}
		if($poster['subcredit'] && $_SESSION['uid']){
			$tag='subcredit'.$id;
			$subcredit=pdo_getcolumn('core_credit_log',array('mid'=>$_SESSION['uid'],'tag'=>$tag,'plugin'=>'jy_poster','uniacid'=>$_SESSION['uniacid']),'id');
			if(!$subcredit){
				model('core/member')->member_credit($_SESSION['uid'],'credit1',$poster['subcredit'],true,'jy_poster','关注人海报扫码关注',$tag);
			}
		}
		if($poster['submoney'] && $_SESSION['uid']){
			$tag='submoney'.$id;
			$submoney=pdo_getcolumn('core_credit_log',array('mid'=>$_SESSION['uid'],'tag'=>$tag,'plugin'=>'jy_poster','uniacid'=>$_SESSION['uniacid']),'id');
			if(!$submoney){
				model('core/member')->member_credit($_SESSION['uid'],'credit2',$poster['submoney'],true,'jy_poster','关注人海报扫码关注',$tag);
			}
		}
		return true;
	}
	public function get_wxappewm($url,$pid){//pid要有唯一性
		if(!$url || !$pid || !$_SESSION['wxapp_id']){
			return false;
		}
		$rootat=ATTACHMENT_TYPE == '0'?ROOT_AT:ATTACHMENT_URL;
		$image='oss/'.$_SESSION['uniacid'].'/images/jy_poster/wxapp'.$_SESSION['uid'].'g'.$pid.'.jpg';
		$isadd=cfc('files')->source_check($image);
		if(!$isadd){
			$wxapp=pdo_get('core_account_wxapp',array('id'=>$_SESSION['wxapp_id'],'uniacid'=>$_SESSION['uniacid']));
			$res=model('core/wxapp')->appcode($url,$wxapp['appid'],$wxapp['appsecret'],200);
			$path='oss/'.$_SESSION['uniacid'].'/images/jy_poster';
			if(!file_exists($rootat.$path) && ATTACHMENT_TYPE == '0'){
					mkdir(ROOT_AT.$path,0700, true);
			}
			if($res){
				$filename=$path.'/wxapp'.$_SESSION['uid'].'g'.$pid.'.jpg';
				cfc('files')->source_save($res,'nochoose','png','二维码',$filename,'',$url);
			}
		}
		$ewm='oss/'.$_SESSION['uniacid'].'/images/jy_poster/wxapp'.$_SESSION['uid'].'g'.$pid.'.jpg';
		return $ewm;
	}
}
?>